from flask import jsonify, request
from recommendation_api import RecommendationAPI
from datetime import datetime
import pymysql

# 数据库配置
db_config = {
    'host': 'localhost',
    'user': 'root',
    #'password': 'Zhangjingyi0916@',
    'password': 'yunxi246810',
    'database': 'double_create'
}

# 初始化推荐API
recommendation_api = RecommendationAPI(db_config)

DBHOST = db_config['host']
DBUSER = db_config['user']
DBPASS = db_config['password']
DBNAME = db_config['database']


def register_recommendation_routes(app):
    """
    注册推荐系统相关的路由

    参数:
        app: Flask应用实例
    """

    @app.route('/api/recommend_outfit', methods=['POST'])
    def recommend_outfit():
        """获取服装搭配推荐"""
        try:
            data = request.get_json()

            # 获取必要参数
            user_id = data.get('user_id')
            if not user_id:
                return jsonify({"error": "用户ID不能为空"}), 400

            # 获取可选参数
            weather = data.get('weather')
            temperature = data.get('temperature')
            theme = data.get('theme')
            date = data.get('date')
            season = data.get('season')
            n_recommendations = data.get('n_recommendations', 1)
            random_seed = data.get('random_seed')  # 获取随机种子

            # 如果提供了随机种子，设置numpy随机种子
            if random_seed is not None:
                import numpy as np
                np.random.seed(random_seed)
                import random
                random.seed(random_seed)

            # 调用推荐API
            try:
                recommendations, error_info = recommendation_api.get_outfit_recommendation(
                    user_id=user_id,
                    weather=weather,
                    temperature=temperature,
                    theme=theme,
                    date=date,
                    season=season,
                    n_recommendations=n_recommendations
                )
            except ValueError as e:
                # 处理可能的解包错误
                print(f"推荐API返回值错误: {e}")
                recommendations = []
                error_info = {"error_code": "API_ERROR", "error_message": "推荐系统返回值错误"}

            # 如果有错误信息，返回错误信息
            if error_info:
                return jsonify({
                    "message": "获取推荐失败",
                    "error": error_info,
                    "recommendations": []
                }), 200  # 仍使用200状态码，让前端根据error字段判断

            return jsonify({
                "message": "获取推荐成功",
                "recommendations": recommendations
            }), 200

        except Exception as e:
            print(f"推荐出错: {e}")
            return jsonify({"error": f"获取推荐失败: {str(e)}"}), 500

    @app.route('/api/outfit_feedback', methods=['POST'])
    def outfit_feedback():
        """处理用户对搭配的反馈"""
        try:
            data = request.get_json()

            # 获取必要参数
            user_id = data.get('user_id')
            clothes_ids = data.get('clothes_ids')
            rating = data.get('rating')  # rating 现在是可选的

            if not user_id or not clothes_ids:
                return jsonify({"error": "用户ID和衣物ID列表不能为空"}), 400

            # 如果提供了评分，验证评分范围
            if rating is not None:
                try:
                    rating = float(rating)
                    if rating < 1 or rating > 5:
                        return jsonify({"error": "评分必须在1-5之间"}), 400
                except ValueError:
                    return jsonify({"error": "评分必须是数字"}), 400

            # 获取可选参数
            theme = data.get('theme')

            # 调用反馈API
            success, message = recommendation_api.provide_feedback(
                user_id=user_id,
                clothes_ids=clothes_ids,
                rating=rating,  # 可以是 None
                theme=theme
            )

            if success:
                return jsonify({"message": message}), 200
            else:
                return jsonify({"error": message}), 400

        except Exception as e:
            print(f"处理反馈出错: {e}")
            return jsonify({"error": f"处理反馈失败: {str(e)}"}), 500

    @app.route('/api/refresh_catalog', methods=['POST'])
    def refresh_catalog():
        """刷新服装目录"""
        try:
            success, message = recommendation_api.refresh_catalog()
            return jsonify({"message": message}), 200
        except Exception as e:
            return jsonify({"error": f"刷新服装目录失败: {str(e)}"}), 500

    @app.route('/api/similar_outfits', methods=['POST'])
    def get_similar_outfits():
        """获取与指定搭配相似的其他搭配"""
        try:
            data = request.get_json()

            # 验证必要字段
            if not data.get('outfit_id'):
                return jsonify({"error": "缺少必要字段 (outfit_id)"}), 400

            outfit_id = data.get('outfit_id')
            n_recommendations = data.get('n_recommendations', 3)

            # 获取搭配对象
            conn = pymysql.connect(
                host=DBHOST,
                user=DBUSER,
                password=DBPASS,
                database=DBNAME,
                cursorclass=pymysql.cursors.DictCursor
            )

            with conn:
                with conn.cursor() as cursor:
                    # 获取搭配中的衣物
                    sql = """
                    SELECT clothes_id FROM outfit_items 
                    WHERE outfit_id = %s
                    """
                    cursor.execute(sql, (outfit_id,))
                    clothes_ids = [item['clothes_id'] for item in cursor.fetchall()]

                    if not clothes_ids:
                        return jsonify({"error": "搭配不存在或不包含衣物"}), 404

            # 创建搭配对象
            outfit = recommendation_api.recommendation_system.create_outfit_from_ids(clothes_ids)
            if not outfit:
                return jsonify({"error": "无法创建搭配对象"}), 500

            # 获取相似搭配
            similar_outfits = recommendation_api.recommendation_system.get_similar_outfits(outfit, n=n_recommendations)

            # 格式化返回结果
            result = []
            for similar_outfit in similar_outfits:
                outfit_items = []
                for item in similar_outfit.items:
                    outfit_items.append({
                        'clothes_id': item.clothes_id,
                        'category': item.category,
                        'subcategory': item.subcategory,
                        'image_url': recommendation_api._get_image_url(item.clothes_id)
                    })

                result.append({
                    'outfit_id': similar_outfit.outfit_id,
                    'clothes_ids': [item['clothes_id'] for item in outfit_items],
                    'items': outfit_items
                })

            return jsonify({
                "message": "获取相似搭配成功",
                "similar_outfits": result
            }), 200

        except Exception as e:
            print(f"获取相似搭配出错: {e}")
            return jsonify({"error": f"获取相似搭配失败: {str(e)}"}), 500
